package service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;

import core.NewOptions;

/**
 * Service permettant de g�rer les options du projet.
 * 
 * @author sebastien
 */
public class OptionsServiceImpl implements OptionsService {

	// Logger
	private static Logger LOGGER = LoggerFactory.getLogger(OptionsService.class);

	/** Default options file name */
	private static final String OPTIONS_FILE = "options.xml";
	/** Default directory */
	private static final String DIR = "src/main/resources/";

	public File save(NewOptions options) {
		return save(options, OPTIONS_FILE);
	}

	/**
	 * @param options
	 * @param name
	 * @return
	 */
	public File save(NewOptions options, String name) {

		File optionsFile = new File(DIR + name);
		try {
			XStream xstream = getInstance();
			FileWriter fos = new FileWriter(optionsFile);
			try {
				xstream.toXML(options, fos);
				LOGGER.debug("Save options : {} to {}", options, optionsFile.toURI());
			} finally {
				fos.close();
			}

		} catch (FileNotFoundException e) {
			LOGGER.debug(e.getLocalizedMessage());
		} catch (IOException ioe) {
			LOGGER.debug(ioe.getLocalizedMessage());
		}

		return optionsFile;

	}

	public NewOptions load() {
		return load(OPTIONS_FILE);
	}

	/**
	 * @param name
	 * @return
	 */
	public NewOptions load(String name) {

		NewOptions options = null;
		File optionsFile = new File(DIR + name);
		try {
			XStream xstream = getInstance();
			FileReader fis = new FileReader(optionsFile);
			try {
				options = (NewOptions) xstream.fromXML(fis);
				LOGGER.debug("Loaded options : {} ", options, optionsFile.toURI());
			} finally {
				fis.close();
			}

		} catch (FileNotFoundException e) {
			LOGGER.debug(e.getLocalizedMessage());
		} catch (IOException ioe) {
			LOGGER.debug(ioe.getLocalizedMessage());
		}

		return options;

	}

	/**
	 * Retourne l'instance de création/suppression d'options
	 * 
	 * @return
	 */
	public XStream getInstance() {
		XStream xstream = new XStream();
		xstream.alias("options", NewOptions.class);
		xstream.registerConverter(new OptionsConverter());
		return xstream;
	}

}
